//
// Created by Administrator on 2024/11/6.
//

#include <cstring>
#include <filesystem>
#include "CompressZip.h"



std::vector<std::string> CompressZip::decompressZip(const char *zip_filename, const char *output_dir) {

    std::vector<std::string> tmp_files;
    int err = 0;
    struct zip *archive = zip_open(zip_filename, 0, &err);
    if (archive == nullptr) {
        throw std::runtime_error("无法打开 ZIP 文件: " + std::string(zip_filename));
    }

    zip_int64_t num_files = zip_get_num_entries(archive, 0);
    for (zip_int64_t i = 0; i < num_files; i++) {
        struct zip_stat stat{};
        if (zip_stat_index(archive, i, 0, &stat) != 0) {
            throw std::runtime_error("无法获取 ZIP 文件的统计信息");
        }

        struct zip_file *zf = zip_fopen_index(archive, i, 0);
        if (zf == nullptr) {
            throw std::runtime_error("无法打开文件: " + std::string(stat.name));
        }

        std::filesystem::path p(stat.name);
        if(p.filename().empty()){
            continue;
        }


        char output_path[1024];
        snprintf(output_path, sizeof(output_path), "%s/%s", output_dir, p.filename().c_str());


        FILE *out_file = fopen(output_path, "wb");
        if (out_file == nullptr) {
            zip_fclose(zf);
            throw std::runtime_error("无法创建文件: " + std::string(output_path));
        }


        char buffer[8192];
        zip_int64_t bytes_read;
        while ((bytes_read = zip_fread(zf, buffer, sizeof(buffer))) > 0) {
            fwrite(buffer, 1, bytes_read, out_file);
        }

        tmp_files.emplace_back(output_path);
        fclose(out_file);
        zip_fclose(zf);
    }

    zip_close(archive);

    return tmp_files;
}
